#include "drv_exti.h"
#include "drv_systick.h"  // 包含延时函数声明，消除隐式警告
void drv_extif9_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    EXTI_InitTypeDef EXTI_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    //RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); //开启GPIOF的时钟
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); //开启GPIOC的时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); //开启SYSCFG的时
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_8 | GPIO_Pin_5;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOF, &GPIO_InitStruct);
    GPIO_Init(GPIOC, &GPIO_InitStruct);

    //配置EXTI外部中断控制管家(上升下降沿的选择,是否屏蔽中断,选择哪条线给NVI
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource9);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource8);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource5);

    EXTI_InitStruct.EXTI_Line = EXTI_Line9 | EXTI_Line8 | EXTI_Line5;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt; //设置工作模式为中断模式
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling; //设置触发方式为上升
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI9_5_IRQn; //指定中断通道
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0; //设置抢占优先级为
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0; //设置响应优先级为0
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
} // end drv_exti9_init



// 轮询检测 GPIOC9 按键（带消抖）
uint8_t drv_key_c9_poll(void)
{
    static uint8_t key_state = 1;  // 1：未按下，0：按下
    uint8_t current_state = GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_9);

    if (current_state != key_state)
    {
        drv_systick_ms(20);  // 消抖延时
        if (GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_9) == current_state)
        {
            key_state = current_state;
            if (current_state == 0)  // 按下（高→低）
            {
                return 1;
            }
        }
    }
    return 0;
}

